package com.ysx.TrainSchedulesAndTicketSales.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.ysx.TrainSchedulesAndTicketSales.domain.TrainStation;
import com.ysx.TrainSchedulesAndTicketSales.domain.TrainStationExample;
import com.ysx.TrainSchedulesAndTicketSales.mapper.TrainStationMapper;
import com.ysx.TrainSchedulesAndTicketSales.req.TrainStationQueryReq;
import com.ysx.TrainSchedulesAndTicketSales.req.TrainStationSaveReq;
import com.ysx.TrainSchedulesAndTicketSales.resq.TrainStationQueryResp;
import com.ysx.common.exception.BusinessException;
import com.ysx.common.exception.BusinessExceptionEnum;
import com.ysx.common.repentity.PageResp;
import com.ysx.common.util.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 列车车站服务类
 * 提供列车车站信息的保存、查询、删除等业务逻辑处理
 */
@Service
public class TrainStationService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainStationService.class);

    @Resource
    private TrainStationMapper trainStationMapper;

    /**
     * 保存列车车站信息
     * 如果ID为空则新增，否则更新已有记录
     * 在新增时会校验同车次站序和站名的唯一性
     * 
     * @param req 列车车站保存请求参数
     */
    public void save(TrainStationSaveReq req) {
        DateTime now = DateTime.now();
        TrainStation trainStation = BeanUtil.copyProperties(req, TrainStation.class);
        if (ObjectUtil.isNull(trainStation.getId())) {

            // 保存之前，先校验唯一键是否存在
            TrainStation trainStationDB = selectByUnique(req.getTrainCode(), req.getIndex());
            if (ObjectUtil.isNotEmpty(trainStationDB)) {
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_STATION_INDEX_UNIQUE_ERROR);
            }
            // 保存之前，先校验唯一键是否存在
            trainStationDB = selectByUnique(req.getTrainCode(), req.getName());
            if (ObjectUtil.isNotEmpty(trainStationDB)) {
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_STATION_NAME_UNIQUE_ERROR);
            }

            trainStation.setId(SnowUtil.getSnowflakeNextId());
            trainStation.setCreateTime(now);
            trainStation.setUpdateTime(now);
            trainStationMapper.insert(trainStation);
        } else {
            trainStation.setUpdateTime(now);
            trainStationMapper.updateByPrimaryKey(trainStation);
        }
    }

    /**
     * 根据车次代码和站序查询列车车站信息
     * 
     * @param trainCode 车次代码
     * @param index 站序
     * @return 列车车站信息对象，如果不存在则返回null
     */
    private TrainStation selectByUnique(String trainCode, Integer index) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andIndexEqualTo(index);
        List<TrainStation> list = trainStationMapper.selectByExample(trainStationExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据车次代码和站名查询列车车站信息
     * 
     * @param trainCode 车次代码
     * @param name 站名
     * @return 列车车站信息对象，如果不存在则返回null
     */
    private TrainStation selectByUnique(String trainCode, String name) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andNameEqualTo(name);
        List<TrainStation> list = trainStationMapper.selectByExample(trainStationExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 分页查询列车车站信息列表
     * 根据查询条件分页获取列车车站信息，并按车次代码和站序升序排列
     * 
     * @param req 列车车站查询请求参数，包含分页信息和查询条件
     * @return PageResp<TrainStationQueryResp> 分页列车车站信息列表
     */
    public PageResp<TrainStationQueryResp> queryList(TrainStationQueryReq req) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.setOrderByClause("train_code asc, `index` asc");
        TrainStationExample.Criteria criteria = trainStationExample.createCriteria();
        if (ObjectUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }

        LOG.info("查询页码: {}", req.getPage());
        LOG.info("每条条数: {}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<TrainStation> trainStationList = trainStationMapper.selectByExample(trainStationExample);

        PageInfo<TrainStation> pageInfo = new PageInfo<>(trainStationList);
        LOG.info("总行数: {}", pageInfo.getTotal());
        LOG.info("总页数: {}", pageInfo.getPages());

        List<TrainStationQueryResp> list = BeanUtil.copyToList(trainStationList, TrainStationQueryResp.class);

        PageResp<TrainStationQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 根据ID删除列车车站信息
     * 
     * @param id 要删除的列车车站ID
     */
    public void delete(Long id) {
        trainStationMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据车次代码查询列车车站列表
     * 按站序升序排列
     * 
     * @param trainCode 车次代码
     * @return 列车车站信息列表
     */
    public List<TrainStation> selectByTrainCode(String trainCode) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.setOrderByClause("`index` asc");
        trainStationExample.createCriteria().andTrainCodeEqualTo(trainCode);
        return trainStationMapper.selectByExample(trainStationExample);
    }
}